<template>
  <div class="dynamic_form_item">
      
      <a-form-item :name="props.question.key">
        <template v-slot:label>
          <label for="">{{ props.question.label }}</label>
        </template>
        <a-switch
          @change="changeMethod"
          v-model:checked="props.question.value"
          :disabled="props.question.disabled"
          :checkedChildren="props.question.state.activeText"
          :unCheckedChildren="props.question.state.inactiveText"
          :checkedValue="props.question.state.activeValue"
          :unCheckedValue="props.question.state.inactiveValue"
           >
        </a-switch>
        <div class="dynamic_form_hint" v-if="props.question.hint">
          {{ props.question.hint }}
        </div>
      </a-form-item>
  </div>
</template>
<script setup lang="ts">
import { watch,getCurrentInstance,onMounted,onUnmounted} from "vue";
import { QuestionBase } from "../../../question-base";
import { filter } from 'rxjs/operators';
import { Subscription } from 'rxjs';
import { message } from "ant-design-vue";
import { INFOSERVE } from "@/mixins/subject/subject-types";

//subject变量
let $subscribeSub: Subscription;
let fromInfo:any = {};

const { proxy  }:any = getCurrentInstance()
let props = defineProps<{ question: QuestionBase<any>,formData:any}>();
const emit = defineEmits([ "update:formData"]);
watch(()=>props.question.value, (val)=>{
    emit('update:formData', val);
},{ flush:'sync' })



onMounted(() => {
  subWatch();
})

//解绑
onUnmounted(()=>{
  if ($subscribeSub != undefined) {
    $subscribeSub.unsubscribe();
  }
})

//获取数据
function changeMethod(){
    //自动请求接口
    if(props.question.state.url){
      let para:any = {};
      //有params就按照params传参数没有就正常传自己
      if( props.question.state.params ){
        for (let key in props.question.state.params) {
          para[key] = fromInfo[props.question.state.params[key]];
        }
      }
      para[props.question.key] = props.question.value;
      if( props.question.state.assign ){
        para = Object.assign( {}, para, props.question.state.assign);
      }
      proxy.$Http.api(props.question.state.url, para, props.question.state.protType ? props.question.state.protType : 'post').then((data: any) => {
        message.success('修改成功！');
      });
    }
}

//监听动态表单数据完成
function subWatch() {
    $subscribeSub = proxy.$NotificationFormSub
      .getParams()
      .pipe(filter((res: any) => res !== 0))
      .subscribe((item: any) => {
        try {
          if( item.key === INFOSERVE){  //数据都全部都到了
            if( item.value ){
              fromInfo = item.value[props.question.key];
            }
          }
        } catch (error) {
          
        }
      })
}

</script>

<style lang="less" scoped>
@import url('./input-switch.component.less');
</style>
